#include <QApplication>
#include <QQmlApplicationEngine>
#include <thread>
#include <unistd.h>
#include <signal.h>
#include "CamControl.h"
#include "ImageDetect.h"
#include "TerminalControl.h"
#include "CommEpollManage.h"
#include "DisplayControl.h"

#include "V4l2Device.h"
#include "CamGainControl.h"
#include "ProtocolMCU.h"
#include "SerialPortQt.h"
#include "StatusStore.h"

#include "DisPlayContent.h"
#include "OpenCVFrame.h"
//#include "beziercurve.h"
#include "Communicate.h"
#include "FocusControl.h"
#include "vpu.h"


static bool SysInit()
{
    if(!CommInitQt())
    {
        printf("CommInitQt error\n");
        return false;
    }
    if(!CommInitPosix())
    {
        printf("CommInitPosix error\n");
        return false;
    }
    if(!CommEpollManageInit())//包含了通信的初始化,在epoll中读取收到的信息
    {
        printf("EpollManageInit error\n");
        return false;
    }
    CamControl::GetInstance().InitCamera();//初始化相机参数
    InitDisplay();//初始化对比度
    CamGainControl::GetInstance().Init();//增益初始化
    v4lDev.StartReadFrame();//开始读取V4L2视频
    focusCtl.Init();
//    focusCtl.MotoSelfCheck();//自检
//    std::this_thread::sleep_for(std::chrono::milliseconds(15000));
//    InitStatusFromSave();//初始化完成、自检完成后、读取存储值,开始周期存储
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    return true;
}

static bool Rescue(int argc)
{
    setvbuf(stdout,NULL,_IONBF,0);
    printf("version is %.2f\n",1.99);

    if(!SysInit())
    {
        return false;
    }
    ImageDetect::GetInstance().DetectThread();
//    std::thread(EncodeFun).detach();
    TerminalCtlThread(argc);
    return true;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QFont font;
    font.setFamily("SimSun");
    QApplication::setFont(font);

    signal(SIGINT,[](int signal_num)
    {
        printf("catch signal %d\n",signal_num);
        _exit(0);
    });

    if(!Rescue(argc))
    {
        printf("error\n");
        return -1;
    }
    qmlRegisterType<OpenCVFrame>("TH.OpenCVFrame", 1, 0, "OpenCVFrame");
    qmlRegisterType<DisPlayContent>("TH.DisPlayContent", 1, 0, "DisPlayContent");
//    qmlRegisterType<BezierCurve>("CustomGeometry", 1, 0, "BezierCurve");
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}
